package com.example.rs485demo.controller;

import cn.hutool.core.util.HexUtil;
import com.example.rs485demo.util.*;
import com.example.rs485demo.util.PortInit;
import com.example.rs485demo.util.SerialPortUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.ByteBuffer;
import java.util.Locale;

/**
 * Demo class
 *
 * @author XDRS
 * @date 2023/3/30 15:50
 */
@RestController
public class OpenController {


    @GetMapping(value = "open")
    public void test(Integer code) {
        SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
        byte[] HEX = getHex(code);
        serialPortUtil.sendToPort(PortInit.serialPort, HEX);
    }

    private byte[] getHex(Integer code) {
        String s = "8A";
        if(code>0 && code<25){
            s += "01";
        }else if(code>24 && code<49){
            s += "02";
        }else if(code>48 && code<73){
            s += "03";
        }
        s += code2Hex(code) +"11";
        s += BBCUtil.getBCCStr(s);
        System.out.println(s);
        byte[] HEX = hexStr2Byte(s);
        return HEX;
    }

    /**
     * 定时任务，间隔5分钟采集一次数据
     */
//    @Scheduled(cron = "0 0/5 * * * ?")
//    public void send() {
//        System.out.println("send ok");
//        SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
//        byte[] HEX = hexStr2Byte("000300040002841B");
//        serialPortUtil.sendToPort(PortInit.serialPort, HEX);
//
//    }
    /**
     * 十六进制字符串转byte[]
     *
     * @param hex 十六进制字符串
     * @return byte[]
     */
    public static byte[] hexStr2Byte(String hex) {
        if (hex == null) {
            return new byte[]{};
        }

        // 奇数位补0
        if (hex.length() % 2 != 0) {
            hex = "0" + hex;
        }

        int length = hex.length();
        ByteBuffer buffer = ByteBuffer.allocate(length / 2);
        for (int i = 0; i < length; i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr, 16);
            buffer.put(b);
        }
        return buffer.array();
    }
    private String code2Hex(Integer code){
        String s = HexUtil.toHex(code).toUpperCase(Locale.ROOT);
        if(s.length()<2){
            s = "0" + s;
        }
        return s;
    }
}